package design.simdi.code.final_paper.core.entities;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

/**
 * 
 * @author Marius Dumitriu - (Jun 21, 2010 - 12:31:37 PM)
 * 
 */
@Entity
@Table(name = "ideas")
@AttributeOverrides( { @AttributeOverride(name = "id", column = @Column(name = "Idea_Id")) })
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Idea extends ApplicationEntity {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String name;
	private String description;
	private Set<Keyword> keywords;
	private Set<Bibliography> bibliographies;
	private Person person;
	@Transient
	private String keywordsAsString;

	@Column(length = 250, nullable = false, name = "Name")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Column(length = 250, name = "Description")
	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	@ManyToOne
	@JoinColumn(name = "Person_Fk")
	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public void setKeywords(Set<Keyword> keywords) {
		this.keywords = keywords;
	}

	@OneToMany
	@JoinColumn(name = "Idea_FK")
	public Set<Keyword> getKeywords() {
		return keywords;
	}

	@Transient
	private String getKeyWordsAsString() {
		if (getKeywords() == null)
			return "";
		StringBuilder sb = new StringBuilder();
		List<Keyword> lista = new ArrayList<Keyword>(getKeywords());
		Collections.sort(lista, new Comparator<Keyword>() {

			public int compare(Keyword o1, Keyword o2) {
				return o1.getName().compareTo(o2.getName());
			}
		});
		for (Keyword keyword : lista)
			sb.append(keyword.getName() + ", ");

		if (sb.length() > 0)
			return sb.toString().substring(0, sb.toString().length() - 2);
		else
			return sb.toString();
	}

	public void setKeywordsAsString(String keywordsAsString) {
		this.keywordsAsString = keywordsAsString;
	}

	@Transient
	public String getKeywordsAsString() {
		keywordsAsString = getKeyWordsAsString();
		return keywordsAsString;
	}

	public void setBibliographies(Set<Bibliography> bibliographies) {
		this.bibliographies = bibliographies;
	}

	@OneToMany
	@JoinColumn(name = "Idea_FK")
	public Set<Bibliography> getBibliographies() {
		return bibliographies;
	}

	public String toString() {
		return name;
	}

}
